/* Copyright Homeaway, Inc 2005-2008. All Rights Reserved.
 * No unauthorized use of this software.
 */
package org.mis6323.data.dao.impl;

import org.mis6323.data.dao.PatientDao;
import org.mis6323.data.model.Patient;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * tvu has not yet bothered to enter a useful javadoc comment.
 */
public class FileBasedPatientDaoImpl extends AbstractFileBasedDaoImpl<Patient>
        implements PatientDao {

    private Long currentId;

    public FileBasedPatientDaoImpl(String fileName) {
        super(fileName);

        // Go through the set of patient loaded to find the largest id
        currentId = 0l;
        for(Patient p : this.data) {
            currentId = Math.max(currentId, p.getId());
        }
    }

    public void createPatient(Patient patient) {
        // since we want to look up patient by phone number
        // enforce that it's unique
        if (this.searchPatientByPhoneNo(patient.getPhoneNo()) != null) {
            throw new IllegalArgumentException("Phone number is already used");
        }
        // increment current id by 1 so that new patient has a unique id
        this.currentId += 1;
        patient.setId(this.currentId);
        this.data.add(patient);

        // immediately flush the content of the data to disc.
        this.flush();
    }

    public void deletePatient(Long patientId) {
        Patient p = this.searchPatientById(patientId);
        if (p != null) {
            this.data.remove(p);
        }
        this.flush();
    }

    public void updatePatient(Patient patient) {
        Patient old = this.searchPatientById(patient.getId());
        if (old == null) {
            throw new IllegalArgumentException("Provided is not saved");
        }
        if (!old.getPhoneNo().equals(patient.getPhoneNo()) &&
                this.searchPatientByPhoneNo(patient.getPhoneNo()) != null) {
            throw new IllegalArgumentException("Phone number is already used");
        }

        this.data.add(patient);
        this.flush();
    }

    public Patient searchPatientById(Long patientId) {
         for (Patient p : this.data) {
            if (p.getId() == patientId) {
                return p;
            }
        }
        return null;
    }

    public Patient searchPatientByPhoneNo(String phoneNo) {
        for (Patient p : this.data) {
            if(p.getPhoneNo().equals(phoneNo)) {
                return p;
            }
        }
        return null;
    }
}
